<template>
  <div>
    <ChatBox />
  </div>
</template>

<script setup>
import { generateMockUsersData } from '../mock/chat.js'
import { ref } from 'vue'
import { RealtimeClient, SSEAdapter, WebSocketAdapter, FetchSSEAdapter } from '../../libs/index.js';
import ChatBox from '../components/ChatBox.vue';

// 生成模拟用户数据
const mockUsers = generateMockUsersData();


// 初始化SSE客户端
// const wsClient = new RealtimeClient(WebSocketAdapter, {
//   url: 'ws://localhost:8081',
//   format: 'json',
  
//   // 重连配置
//   maxReconnectAttempts: Infinity, // 无限重试
//   reconnectDecay: 2,
  
//   // 心跳配置
//   heartbeatInterval: 25000,
//   heartbeatTimeout: 8000
// });

// 监听所有事件
// wsClient.on('open', () => console.log('Connected'));
// wsClient.on('message', data => console.log('Message:', data));
// wsClient.on('close', () => console.log('Disconnected'));
// wsClient.on('error', err => console.error('Error:', err));
// wsClient.on('reconnecting', (attempt, delay) => {
//   console.log(`Reconnecting attempt ${attempt} in ${delay}ms`);
// });

// wsClient.connect();
// 发送消息
// wsClient.send({ type: 'text', content: 'Hello' });

// sseClient
const sseClient = new RealtimeClient(SSEAdapter, {
  url: 'http://localhost:3000/sse',
  format: 'json',
  events: ['notification', 'alert'] // 监听自定义事件
});
console.log('SSE 客户端启动');

// const sseClient = new RealtimeClient(FetchSSEAdapter, {
//   url: 'http://localhost:3000/sse',
//   format: 'json',
//   // headers: { 'Authorization': 'Bearer xxx' },
//   // method: 'POST', // GET/POST
//   //// body: JSON.stringify({ userId: 123 }),
//   // 重试配置
//   maxRetries: 5,
//   retryDelay: 3000,
//   retryBackoffFactor: 2,
  
//   // 心跳配置
//   heartbeatInterval: 10000,  // 每10秒检查一次
//   heartbeatTimeout: 45000    // 45秒无数据视为超时
// });



sseClient.on('reconnecting', (attempt, delay) => {
  console.log(`第 ${attempt} 次重试，等待 ${delay}ms`);
});

sseClient.on('error', err => {
  if (err.message.includes('Heartbeat')) {
    console.error('连接失去响应，正在尝试恢复...');
  }
});

// 监听服务端事件
sseClient.on('init', (data) => {
  console.log('初始化连接:', data.id);
});

sseClient.on('message', (data) => {
  console.log('接收到消息:', data);
});

sseClient.on('error', (err) => {
  console.error('连接异常:', err.message);
});

// 启动连接
sseClient.connect();

// 30秒后断开测试
setTimeout(() => {
  sseClient.disconnect();
  console.log('测试连接已主动断开');
}, 1000 * 60 * 10);

</script>